import { getStyle } from '@/utils/tools'
export default {
  mounted(el: HTMLElement, binding: any) {
    const preview = el
    // 获取放大镜元素
    const magnifier = el.querySelector('.mask') as HTMLElement
    // 获取放大图片
    const view = document.querySelector('.magnifier') as HTMLElement
    const img = view.querySelector('img') as HTMLElement
    const magWidth = getStyle(magnifier, 'width')
    const magHeight = getStyle(magnifier, 'height')
    const previewWidth = getStyle(preview, 'width')
    const previewHeight = getStyle(preview, 'height')

    const init = () => {
      bindEvent()
    }

    function bindEvent() {
      preview.addEventListener('mouseover', (e: MouseEvent) => {
        magnifier.style.display = 'block'
        magnifier.style.position = 'absolute'
        magnifier.style.left = `0`
        magnifier.style.top = `0`

        view.style.display = 'block'

        const { x, y, mouseX, mouseY } = getPosition(e)
        showMagnifier(x, y, mouseX, mouseY)
        document.addEventListener('mousemove', handleMouseMove, false)
      })
      preview.addEventListener('mouseout', handleMouseOut, false)
    }

    function handleMouseMove(e: MouseEvent) {
      const { x, y, mouseX, mouseY } = getPosition(e)
      showMagnifier(x, y, mouseX, mouseY)
    }

    function handleMouseOut() {
      magnifier.style.display = 'none'
      view.style.display = 'none'
      document.removeEventListener('mousemove', handleMouseMove, false)
    }

    function showMagnifier(
      x: number,
      y: number,
      mouseX: number,
      mouseY: number
    ) {
        let maskMaxLeft = previewWidth - magnifier.offsetWidth
        let maskMaxTop = previewHeight - magnifier.offsetHeight
        if (mouseX - magWidth / 2 < 0) {
          x = 0
        } else if (mouseX + magWidth / 2 >= previewWidth) {
          x = maskMaxLeft
        }
        if (mouseY - magHeight / 2 < 0) {
          y = 0
        } else if (mouseY + magHeight / 2 >= previewHeight) {
          y = maskMaxTop
        }
        magnifier.style.left = `${x}px`
        magnifier.style.top = `${y}px`
        let bigMax = img.offsetWidth - view.offsetWidth
        let bigX = (x * bigMax) / maskMaxLeft
        let bigY = (y * bigMax) / maskMaxLeft
        img.style.left = `-${bigX}px`
        img.style.top = `-${bigY}px`
    }

    function getPosition(e: MouseEvent) {
      return {
        x: e.offsetX - magWidth / 2,
        y: e.offsetY - magHeight / 2,
        mouseX: e.offsetX,
        mouseY: e.offsetY,
      }
    }

    init()
  },
}
